<template>
  <el-dialog
    v-if="load"
    title="推荐物流渠道"
    v-model="visible"
    align-center
    width="1200px"
    @close="close"
    height="600px"
    :z-index="2002"
  >
    <div class="flex justify-between">
      <div>
        <el-select
          class="!w-[160px] radius-right-0 mr-2"
          v-model="queryForm.transport_type"
          clearable
          placeholder="请选择运输方式"
          filterable
          @change="changeHead"
        >
          <el-option
            v-for="item in channel_options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <SelectWarehouse
          class="!w-[160px] mr-2"
          v-model="queryForm.warehouse"
          placeholder="请选择发货仓库"
          @change="changeHead"
        ></SelectWarehouse>
        <el-select
          class="!w-[160px] radius-right-0 mr-2"
          v-model="queryForm.channel_id"
          clearable
          placeholder="请选择渠道名称"
          filterable
          @change="changeHead"
        >
          <el-option
            v-for="item in channelOptions"
            :key="item.id"
            :label="item.channel_name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="flex items-center">
        <div class="mr-2">采购数量：{{ queryForm.sku_quantity }}</div>
        <div class="mr-2">单品毛重：{{ queryForm.package_weight }} g</div>
        <div class="mr-2">
          包装尺寸：{{ queryForm.length }}*{{ queryForm.width }}*{{ queryForm.height }}cm
        </div>
        <div class="mr-2">目的国家：{{ queryForm.destination_country }}</div>
        <div class="mr-2">物流属性：{{ queryForm.goods_attrs_text }}</div>
      </div>
    </div>
    <VTable ref="tableRef" v-bind="tableOptins"> </VTable>
    <template #footer>
      <el-button @click="close">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script lang="jsx" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { feeTrialCalcFreight, tmsOptions } from "@/api/index.js";
import { nextTick } from "vue";
import { channel_options } from "@/utils/data.js";
import SelectWarehouse from "@/components/SelectWarehouse/index.vue";

const emit = defineEmits(["checked"]);
const data = reactive({
  load: false,
  visible: false,
  queryForm: {},
  channelOptions: [],
});

const { load, visible, queryForm, channelOptions } = toRefs(data);

// 打开弹窗
const open = async (form) => {
  queryForm.value = form;
  console.log(form);
  if (!load.value) {
    load.value = true;
    await 1;
  }
  query();
  visible.value = true;
};
// 关闭弹窗
const close = () => {
  visible.value = false;
};

const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  height: 500,
  rowConfig: {
    height: 50,
  },
  columns: [
    {
      title: "操作",
      width: 80,
      slots: {
        default: ({ row }) => {
          return (
            <el-button type="primary" text onClick={() => handleChecked(row)}>
              选择
            </el-button>
          );
        },
      },
    },
    {
      title: "物流渠道名称",
      width: 200,
      slots: {
        default: ({ row }) => {
          return <vText value={row.channel_name}></vText>;
        },
      },
    },
    {
      field: "freight_cny",
      title: "预估运费（CNY）",
      width: 140,
      slots: {
        default: ({ row }) => {
          return (
            <el-button type="primary" link onClick={() => handleCheckFee(row)}>
              {row.freight_cny} CNY
            </el-button>
          );
        },
      },
    },
    {
      field: "warehouse_name",
      title: "发货仓",
      width: 80,
    },
    {
      field: "destination_country",
      title: "区域",
      width: 80,
    },
    {
      field: "time_limit",
      title: "时效（天）",
      width: 80,
    },
    {
      field: "volume",
      title: "体积（CBM）",
      width: 80,
    },
    {
      field: "volume_weight",
      title: "体积重（g）",
      width: 80,
    },
    {
      field: "weight",
      title: "包裹重（g）",
      width: 80,
    },
    {
      field: "real_weight",
      title: "计费重（g）",
      width: 80,
    },
    {
      field: "count_reason",
      title: "抛重值",
      width: 80,
    },
    {
      field: "count_reason_ratio",
      title: "抛比",
      width: 80,
    },
    {
      field: "far_fee",
      title: "偏远地址（CNY）",
      width: 80,
    },
    {
      field: "todo",
      title: "关税（CNY）",
      width: 80,
    },
  ],
  scrollHideForm: false,
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        const res = await feeTrialCalcFreight({ ...form, ...page, ...queryForm.value });
        const sortedData = res.data
          .filter((i) => i.freight && i.freight_cny)
          .filter((i) => !form.transport_type || i.transport_type === form.transport_type)
          .sort((a, b) => {
            const numA = Number(a.freight_cny) || 0;
            const numB = Number(b.freight_cny) || 0;
            return numA - numB;
          });
        return sortedData;
      },
    },
  },
});

const tableRef = ref();
const query = () => {
  nextTick(() => {
    tableRef.value?.query();
  });
};

defineExpose({ open });

// 查看预估运费
const handleCheckFee = (row) => {
  const massageArray = [];

  massageArray.push({
    label: "总运费",
    value: "",
    type: "title",
  });
  for (let key in row?.extend?.total_freight?.detail) {
    massageArray.push({
      label: key,
      value: row?.extend?.total_freight?.detail[key],
    });
  }
  massageArray.push({
    label: "基础费用",
    value: "",
    type: "title",
  });
  for (let key in row.extend?.freight_info?.detail) {
    massageArray.push({
      label: key,
      value: row?.extend?.freight_info?.detail[key],
    });
  }
  massageArray.push({
    label: "附加费",
    value: "",
    type: "title",
  });
  for (let key in row?.extend?.surcharge_details) {
    massageArray.push({
      label: key,
      value: props.data?.extend?.surcharge_details[key],
    });
  }
  ElMessageBox({
    title: "系统金额运费",
    message: () => (
      <div>
        {massageArray.map((d) => {
          if (d.type === "title") {
            return h("p", { style: "font-weight: bold" }, d.label);
          } else {
            return h("p", { style: "padding-left: 10px" }, d.label + ":" + d.value);
          }
        })}
      </div>
    ),
  });
};

// 选择
const handleChecked = (row) => {
  emit("checked", {
    ...row,
    checked_type: queryForm.value.checked_type,
  });
  close();
};

const getChannelList = async () => {
  try {
    const res = await tmsOptions({
      option: "new",
      params: ["map.channel"],
    });
    channelOptions.value = res.data.mapChannel;
  } catch (e) {
    throw Error(e);
  }
};

// 当 channel_id 变化时重新查询数据
const changeHead = () => {
  query();
};

onMounted(() => {
  getChannelList();
});
</script>
